import 'package:flutter/material.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(home: AnimatedListExample());
  }
}

class AnimatedListExample extends StatefulWidget {
  @override
  _AnimatedListExampleState createState() => _AnimatedListExampleState();
}

class _AnimatedListExampleState extends State<AnimatedListExample> {
  List<int> _list = List.generate(5, (index) => index);

  //全局KEY
  GlobalKey<AnimatedListState> _globalKey = GlobalKey();

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text('AnimatedList')),
      body: AnimatedList(
        key: _globalKey,
        initialItemCount: _list.length,
        itemBuilder:
            (BuildContext context, int index, Animation<double> animation) {
              int item = _list[index];
              return FadeTransition(
                opacity: animation,
                child: ListTile(
                  title: Text('早起的年轻人 $item'),
                  leading: Icon(Icons.list),
                  trailing: Icon(Icons.arrow_forward_ios_rounded),
                ),
              );
            },
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: () {},
        child: Icon(Icons.add),
      ),
    );
  }

  _deleteItem() {
    //删除的Item的索引
    int index = 1;
    //保存删除的项
    final removeItem = _list[index];
    //
    _globalKey.currentState?.removeItem(index, (context, animation) {
      return SlideTransition(
        position: Tween(
          begin: Offset(0, 0),
          end: Offset(1, 0),
        ).animate(animation),
        child: ListTile(title: Text('早起的年轻人$removeItem')),
      );
    });
    //源数据删除
    _list.removeAt(index);
  }

  _addItme() {
    _list.add(2000);
    //执行动画
    _globalKey.currentState?.insertItem(_list.length - 1);
  }
}
